<?php

declare(strict_types=1);

namespace App\Chat\Controller;

use App\Chat\Annotation\ChatAuth;
use App\Chat\Dto\ChatLoginDTO;
use App\Chat\Interfaces\ChatUserAuthInterface;
use App\CustHub\Request\LoginRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Mine\MineController;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;

#[Controller('ch/chat/login')]
class LoginController extends MineController
{
    #[Inject]
    protected ChatUserAuthInterface $userAuth;

    /**
     * 自动登录
     * @param LoginRequest $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function autoLogin(LoginRequest $request): ResponseInterface
    {
        return $this->success($this->userAuth->autoLogin($request->all()));
    }

    /**
     * 密码登录
     * @param LoginRequest $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping('passwordLogin')]
    public function passwordLogin(LoginRequest $request): ResponseInterface
    {
        $requestData = $request->validated();
        $dto = new ChatLoginDTO();
        $dto->setAccount($requestData['account']);
        $dto->setPassword($requestData['password']);
        return $this->success($this->userAuth->passwordLogin($dto));
    }

    /**
     * 退出登录
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping("logout"), ChatAuth]
    public function logout(): ResponseInterface
    {
        return $this->userAuth->logout() ?  $this->success('退出成功') : $this->error('退出失败');
    }
}